package com.smart.community.commons.utils;

import java.net.Socket;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import lombok.extern.slf4j.Slf4j;

/**
 * RocketMQ健康检查工具类
 * 用于检测RocketMQ服务的可用性
 * @author Wu.Liang
 * @date 2025年1月20日
 */
@Slf4j
@Component
public class RocketMQHealthChecker {

	@Value("${rocketmq.name-server:127.0.0.1:9876}")
	private String nameServer;

	/**
	 * 检查RocketMQ NameServer是否可用
	 * @return true表示可用，false表示不可用
	 */
	public boolean isNameServerAvailable() {
		try {
			String[] parts = nameServer.split(":");
			String host = parts[0];
			int port = Integer.parseInt(parts[1]);
			
			try (Socket socket = new Socket()) {
				socket.connect(new java.net.InetSocketAddress(host, port), 3000);
				return socket.isConnected();
			}
		} catch (Exception e) {
			log.warn("RocketMQ NameServer连接检查失败: {}:{} - {}", 
				nameServer.split(":")[0], nameServer.split(":")[1], e.getMessage());
			return false;
		}
	}

	/**
	 * 检查RocketMQ服务整体可用性
	 * @return true表示可用，false表示不可用
	 */
	public boolean isRocketMQAvailable() {
		boolean available = isNameServerAvailable();
		if (available) {
			log.debug("RocketMQ服务可用");
		} else {
			log.warn("RocketMQ服务不可用，将使用本地日志");
		}
		return available;
	}

	/**
	 * 异步检查RocketMQ可用性
	 * @param callback 检查完成后的回调
	 */
	public void checkAvailabilityAsync(Runnable callback) {
		new Thread(() -> {
			try {
				boolean available = isRocketMQAvailable();
				if (callback != null) {
					callback.run();
				}
			} catch (Exception e) {
				log.error("异步检查RocketMQ可用性失败: {}", e.getMessage(), e);
			}
		}, "RocketMQ-Health-Check").start();
	}
}
